package au.id.weston.scott.Vincent;

// Copyright (c) 2009, Scott Weston <scott@weston.id.au>
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//     * Neither the name of Scott Weston nor the names of contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import android.app.ExpandableListActivity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class sambasync extends ExpandableListActivity implements View.OnClickListener {

	private final static String TAG = "vincent";
	public static final String PREFS_NAME = "VincentPrefsFile";

	// -------------------------------------------------------------------------------------------
	// -------------------------------------------------------------------------------------------
	// -------------------------------------------------------------------------------------------

	ExpandableListAdapter mAdapter;
	Button mAdd;
	Button mStop;
	Context mContext;
	DatabaseHelper mdbh;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		mContext = this;
		mdbh = new DatabaseHelper(this);
		
		setContentView(R.layout.main);
		mAdd = (Button) findViewById(R.id.add);
		mAdd.setOnClickListener(this);
		mStop = (Button) findViewById(R.id.stop);
		mStop.setOnClickListener(this);

		mAdapter = new ConnectionListAdapter(this, mdbh);
		setListAdapter(mAdapter);
		registerForContextMenu(getExpandableListView());
		
		startService(new Intent(this, sambaservice.class));
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		mdbh.close();
	}

	public class ConnectionListAdapter extends BaseExpandableListAdapter {

		private DatabaseHelper dbh;
        private Cursor c;
        private Context mContext;

		private String[] actions = { "Execute", "Modify", "Associate", "Delete" };
		
		public ConnectionListAdapter(Context context, DatabaseHelper dbHelp) {
            Log.d(TAG, "ConnectionListAdapter(): created...");
            mContext = context;
            dbh = dbHelp;
            c = dbh.queryAll();
            startManagingCursor(c);
        }

		
		public Object getChild(int groupPosition, int childPosition) {
			Log.d(TAG, "getChild()");
			return actions[childPosition];
		}

		public long getChildId(int groupPosition, int childPosition) {
			Log.d(TAG, "getChildId()");
			return childPosition;
		}

		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			Log.d(TAG, "getChildView(): " + groupPosition + ", " + childPosition);
			TextView textView = getGenericView(32);
			textView.setTextSize(20);
			textView.setText(actions[childPosition]);
			textView.setOnClickListener(
					new ConnectionClickListener(groupPosition, childPosition));
			return textView;
		}

		public int getChildrenCount(int groupPosition) {
			Log.d(TAG, "getChildrenCount()");
			return actions.length;
		}

		public Object getGroup(int groupPosition) {
			Log.d(TAG, "getGroup(" + groupPosition + ")");
			try {
				c.moveToPosition(groupPosition);
				return String.format("%s on %s", c.getString(c.getColumnIndex("mount_name")), c.getString(c.getColumnIndex("server")));
			} catch (Exception e) {
				return "error";
			}
		}

		public int getGroupCount() {
			Log.d(TAG, "getGroupCount()");
			return dbh.getCount(c);
		}

		public long getGroupId(int groupPosition) {
			Log.d(TAG, "getGroupId()");
			return groupPosition;
		}

		public TextView getGenericView(int h) {
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, h);

			TextView textView = new TextView(sambasync.this);
			textView.setLayoutParams(lp);
			textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
			textView.setPadding(36, 0, 0, 0);
			return textView;
		}

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			Log.d(TAG, "getGroupView()");
			TextView textView = getGenericView(64);
			textView.setTextSize(24);
			textView.setBackgroundColor(0x80ffffff);
			textView.setTextColor(Color.WHITE);
			textView.setText(getGroup(groupPosition).toString());
			textView.setSingleLine(true);
			return textView;
		}

		public boolean hasStableIds() {
			Log.d(TAG, "hasStableIds()");
			return true;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition) {
			Log.d(TAG, "isChildSelectable()");
			return true;
		}
		
		public class ConnectionClickListener implements View.OnClickListener {
			private int action;
			private int pos;
			
			public ConnectionClickListener(int i, int a) {
				Log.d(TAG, "ConnectionClickListener(): " + i + ", " + a);
				pos = i;
				action = a;
			}

			public void onClick(View arg0) {
				Log.d(TAG, "onClick("+ pos +", "+ action +"): " + arg0.toString());
				c.moveToPosition(pos);
				Log.d(TAG, "  -> " + c.getString(c.getColumnIndex("id")));

				if (action == 0) {
					// create our request
					Intent copy = new Intent(sambaservice.ACTION_COPY);
					copy.putExtra("username", c.getString(c.getColumnIndex("username")));
					copy.putExtra("password", c.getString(c.getColumnIndex("password")));
					copy.putExtra("server", c.getString(c.getColumnIndex("server")));
					copy.putExtra("share", c.getString(c.getColumnIndex("share")));
					copy.putExtra("directory", c.getString(c.getColumnIndex("directory")));
					copy.putExtra("dest", c.getString(c.getColumnIndex("destination")));
					copy.putExtra("mount_name", c.getString(c.getColumnIndex("mount_name")));
					sendBroadcast(copy);
					Toast.makeText(mContext, "Copy queued.  Watch notification bar for progress.", Toast.LENGTH_LONG).show();
				}
			}
		}
	}

	
	@Override
	protected void onResume() {
		super.onResume();
		NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		nm.cancelAll();
	}

//	@Override
//	protected void onPause() {
//	super.onPause();
//	sendBroadcast(new Intent(sambaservice.ACTION_STOP));
//	}

//	@Override
//	protected void onStop() {
//	super.onStop();
//	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//	SharedPreferences.Editor editor = settings.edit();
//	editor.putString("username", username.getText().toString());
//	editor.putString("password", password.getText().toString());
//	editor.putString("server", server.getText().toString());
//	editor.putString("share", share.getText().toString());
//	editor.putString("directory", directory.getText().toString());
//	editor.putString("dest", dest.getText().toString());
//	editor.commit();
//	}

//	@Override
//	protected void onDestroy() {
//	super.onDestroy();
//	sendBroadcast(new Intent(sambaservice.ACTION_STOP));
//	}

	public void onClick(View view) {
		if (view == mAdd) {
			startActivity(new Intent("au.id.weston.scott.Vincent.ADD_CONNECTION"));
		} else if (view == mStop) {
			sendBroadcast(new Intent(sambaservice.ACTION_STOP));
		}
	}

//	try {
//	File test = new File("/sdcard/.vincent");
//	test.createNewFile();
//	test.delete();
//	} catch (Exception e) {
//	new AlertDialog.Builder(this)
//	.setIcon(R.drawable.icon32)
//	.setTitle("SD Card Error")
//	.setMessage("It appears your SD card is not writable.  This program can not copy data " +
//	"to anywhere except SD cards.  Please ensure your SD card is inserted and mounted " +
//	"and that it is not currently mounted on your PC via USB. " +
//	"If you continue to have problems unmount it via the settings tool and then eject " +
//	"and reinsert it before trying again.")
//	.setPositiveButton("ok", new DialogInterface.OnClickListener() {
//	public void onClick(DialogInterface dialog, int whichButton) {
//	/* User clicked OK  */
//	}
//	})
//	.create().show();
//	return;
//	}

//	Log.i(TAG, "Kicking off a copy");

//	// create our request
//	Intent copy = new Intent(sambaservice.ACTION_COPY);
//	copy.putExtra("username", username.getText().toString());
//	copy.putExtra("password", password.getText().toString());
//	copy.putExtra("server", server.getText().toString());
//	copy.putExtra("share", share.getText().toString());
//	copy.putExtra("directory", directory.getText().toString());
//	copy.putExtra("dest", dest.getText().toString());
//	sendBroadcast(copy);
//	Toast.makeText(this, "Copy queued.  Watch notification bar for progress.", Toast.LENGTH_LONG).show();
//	} else if (view == mStop) {
//	sendBroadcast(new Intent(sambaservice.ACTION_STOP));
//	}
//	}
}
